import Vue from 'vue'
import Router from 'vue-router'
import store from '../store' // 导入定义的vuex
import HomeChildren from './children' // 导入子组件
const HomePage = r => require.ensure([], () => r(require('@/components/index')), 'index') // 首页
const Login = r => require.ensure([], () => r(require('@/components/login/login')), 'login') // 登录

Vue.use(Router)

const routes = [
  {
    path: '/',
    name: '首页',
    component: HomePage,
    children: HomeChildren
  },
  {
    path: '/login',
    name: '登录',
    component: Login,
    meta: {
      requireAuth: true
    }
  }
]

const router = new Router({
  routes
})

router.beforeEach((to, from, next) => {
  console.log(to)
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (store.state.token) { // 通过vuex state获取当前的token是否存在
      next()
    } else {
      if (to.path === '/login') { // 如果是登录页面路径，就直接next()
        next()
      } else { // 不然就跳转到登录
        next('/login')
      }
    }
  } else {
    next()
  }
})

export default router
